package com.healthcloud.service.impl;

import java.util.*;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.healthcloud.dao.HospDrAssoMapper;
import com.healthcloud.dao.HospitalDepartmentMapper;
import com.healthcloud.dao.HospitalMapper;
import com.healthcloud.entity.Condition;
import com.healthcloud.entity.HospDrAsso;
import com.healthcloud.entity.Hospital;
import com.healthcloud.entity.HospitalCriteria;
import com.healthcloud.entity.HospitalDepartment;
import com.healthcloud.query.CriteriaUtils;
import com.healthcloud.service.HospitalService;
import com.healthcloud.utils.AreaCodeUtils;
import com.healthcloud.utils.EntityUtils;
import com.healthcloud.utils.HospitalUtil;
import com.healthcloud.utils.PageParam;
import com.healthcloud.utils.Pagine;
import com.healthcloud.vo.DepartmentVo;
import com.healthcloud.vo.HospitalVo;

/**
 * Created by xiam on 2015/6/16.
 */
@Service
@Transactional
public class HospitalServiceImpl implements HospitalService {

	@Autowired
	private HospitalMapper hospitalMapper;

	@Autowired
	private HospitalDepartmentMapper hospitalDepartmentMapper;

	@Autowired
	private HospDrAssoMapper hospDrAssoMapper;

	@Autowired
	private Mapper beanMapper;

	@Override
	public List<Hospital> findByEntityAll(Hospital hospital) {
		return hospitalMapper.findByEntityAll(hospital);
	}

	@Override
	@Transactional
	public Hospital save(Hospital hospital) {
		EntityUtils.initDateTime(hospital);
		hospital.setHosType(HospitalUtil.HOS_TYPE_HOSP);
        hospitalMapper.save(hospital);
		return hospital;
	}

	@Override
	@Transactional
	public Hospital save(Hospital hospital,List<HospitalDepartment> hdList) {
		//新增医院信息
		save(hospital);
		//新增医院与科室关联信息
		int hospId = new Long(hospital.getId()).intValue();
		for(int i=0;i<hdList.size();i++){
			HospitalDepartment hd = hdList.get(i);
			hd.setHosId(hospId);
			hd.setCreatedTime(new Date());
			hd.setUpdatedTime(new Date());
			hospitalDepartmentMapper.save(hd);
		}

		return hospital;
	}

	@Override
	@Transactional
	public void saveBatch(List<Hospital> hosList) {
		List<Hospital> hosAddList = new ArrayList<>();
		List<Hospital> hosUpdateList = new ArrayList<>();
		for (int i = 0; i < hosList.size(); i++) {
			Hospital hospital = hosList.get(i);
			hospital.setHosType(HospitalUtil.HOS_TYPE_HOSP);
			if (hospital.getId() == null) {
				hospital.setCreatedTime(new Date());
				hospital.setUpdatedTime(new Date());
				hosAddList.add(hospital);
			} else {
				hosUpdateList.add(hospital);
			}
		}
		if (hosAddList.size() != 0) {
			hospitalMapper.saveBatch(hosAddList);
		}
		for (int i = 0; i < hosUpdateList.size(); i++) {
			Hospital hospital = hosUpdateList.get(i);
			update(hospital);
		}
	}

	@Override
	@Transactional
	public int update(Hospital hospital) {
		hospital.setUpdatedTime(new Date());
		hospital.setHosType(HospitalUtil.HOS_TYPE_HOSP);
		return hospitalMapper.update(hospital);
	}

	@Override
	@Transactional
	public void update(Hospital hospital, List<HospitalDepartment> hdList) {
		//更新医院信息
		hospital.setUpdatedTime(new Date());
		hospital.setHosType(HospitalUtil.HOS_TYPE_HOSP);
		hospitalMapper.update(hospital);
		//根据医院id查询医院与科室关联信息 oldHdList
		HospitalDepartment oleHd = new HospitalDepartment();
		oleHd.setHosId(new Long(hospital.getId()).intValue());
		List<HospitalDepartment> hdList_old = hospitalDepartmentMapper.findByEntityAll(oleHd);
		//更新医院与科室关联信息
		int hospId = new Long(hospital.getId()).intValue();
		List<HospitalDepartment> hdList_delete = new ArrayList<>();//要删除的 医院与科室关联信息 数据
		List<HospitalDepartment> hdList_update = new ArrayList<>();//要更新的 医院与科室关联信息 数据
		List<HospitalDepartment> hdList_add = new ArrayList<>();//要新增的 医院与科室关联信息 数据

		for (int i = 0; i < hdList.size(); i++) {
			HospitalDepartment hd_new = hdList.get(i);
			boolean b = false;
			for (int j = 0; j < hdList_old.size(); j++) {
				if (hd_new.getDepId().equals(hdList_old.get(j).getDepId())) {
					hdList_update.add(hd_new);
					b = true;
					break;
				}
			}
			if (!b) {
				hdList_add.add(hd_new);
			}
		}

		for (int i = 0; i < hdList_old.size(); i++) {
			HospitalDepartment hd_old = hdList_old.get(i);
			boolean b = false;
			for (int j = 0; j < hdList.size(); j++) {
				if (hd_old.getDepId().equals(hdList.get(j).getDepId())) {
					b = true;
					break;
				}
			}
			if (!b) {
				hdList_delete.add(hd_old);
			}
		}

		//删除医院与科室关联信息
		if(hdList_delete.size()!=0){
			Integer[] hdId_delete = new Integer[hdList_delete.size()];
			Long[] hdId_delete_long = new Long[hdList_delete.size()];
			for (int i = 0; i <hdList_delete.size() ; i++) {
				hdId_delete[i] = hdList_delete.get(i).getId();
				hdId_delete_long[i] = (long)(hdList_delete.get(i).getId());
			}
			hospitalDepartmentMapper.deletes(hdId_delete);//批量删除
			hospDrAssoMapper.deleteByOfficeCodes(hdId_delete_long);//批量删除科室与医生、医院的关联
		}

		//修改医院与科室关联信息
		if(hdList_update.size()!=0){
			for (int i = 0; i <hdList_update.size() ; i++) {
				HospitalDepartment hd = hdList_update.get(i);
				hd.setUpdatedTime(new Date());
				hd.setHosId(hospId);
				hospitalDepartmentMapper.updateByHospIdDepId(hd);
			}
		}

		//新增医院与科室关联信息
		if(hdList_add.size()!=0){
			for(int i=0;i<hdList_add.size();i++){
				HospitalDepartment hd = hdList_add.get(i);
				hd.setHosId(hospId);
				hd.setCreatedTime(new Date());
				hd.setUpdatedTime(new Date());
				hospitalDepartmentMapper.save(hd);
			}
		}

	}

	@Override
	@Transactional
	public int delete(Long id) {
		return hospitalMapper.delete(id);
	}

	@Override
	@Transactional
	public int deletes(Long[] ids) {
		int ja = 0;
		for (int i=0; i<ids.length; i++){
			ja = delete(ids[i]);
		}
		return ja;
	}

	@Override
	@Transactional
	public int logicalDelete(Long id) {
		return hospitalMapper.logicalDelete(id);
	}

	@Override
	@Transactional
	public int logicalDeletes(Long[] ids) {
		for (int i=0; i<ids.length; i++){
			logicalDelete(ids[i]);
		}
		return 0;
	}

	@Override
	public Hospital get(Long id) {
		return hospitalMapper.get(id);
	}

	@Override
	public Page<Hospital> search(HospitalCriteria criteria, Pageable pageable) {
		if (criteria.getAreaCode() != null) {
			Long[] range = AreaCodeUtils.getAreaRange(criteria.getAreaCode());
            criteria.setAreaCodeStart(range[0]);
            criteria.setAreaCodeEnd(range[1]);
		}
        List<Condition<Object>> conditions = CriteriaUtils.getConditions(criteria);
        Pagine<Hospital> page = new Pagine<>(pageable);
		hospitalMapper.criteriaSearch(conditions, page);
		return page;
	}

	@Override
	public List<Hospital> search(Hospital hospital, PageParam pageParam) {
		hospital.setHosType(HospitalUtil.HOS_TYPE_HOSP);
		return hospitalMapper.search(hospital, pageParam);
	}

	@Override
	public int count(Hospital hospital) {
		hospital.setHosType(HospitalUtil.HOS_TYPE_HOSP);
		return hospitalMapper.count(hospital);
	}

	@Override
	public List<Hospital> searchAll(Hospital hospital, PageParam pageParam) {
		return hospitalMapper.search(hospital, pageParam);
	}

	@Override
	public int countAll(Hospital hospital) {
		return hospitalMapper.count(hospital);
	}

	@Override
	public List<Hospital> getHospitalListByAreaCode(String areaCode, Integer hosType) {
		return hospitalMapper.getHospitalListByAreaCode(areaCode, hosType);
	}

	@Override
	public List<Hospital> getAffiliatedHosp(Long id) {
		return hospitalMapper.getAffiliatedHosp(id);
	}

	@Override
	public List<HospitalDepartment> getHospitalDepartmentByHospId(Integer hospId) {
		HospitalDepartment hd = new HospitalDepartment();
		hd.setHosId(hospId);
		return hospitalDepartmentMapper.findByEntityAll(hd);
	}

	@Override
	public List<Hospital> getHospitalsByDrId(Long drId) {
		return hospitalMapper.getHospitalsByDrId(drId);
	}

	@Override
	public List<Hospital> getHospitalsByUserId(Long userId) {
		return hospitalMapper.getHospitalsByUserId(userId);
	}

	@Override
	public List<HospitalVo> getHospitalVosByDrId(Long drId) {
		List<HospitalVo> hospitalVoList = new ArrayList<>();
		List<Hospital> hospitalList = getHospitalsByDrId(drId);//医生所属医院列表
		HospDrAsso hda = new HospDrAsso();
		hda.setDrId(drId);
		List<HospDrAsso> hospDrAssoList = hospDrAssoMapper.findByEntityAll(hda);
		for (int i = 0; i < hospitalList.size(); i++) {
			HospitalVo hospitalVo = new HospitalVo();
			//设置医生所属医院
			hospitalVo.setHospital(hospitalList.get(i));
			//设置医生所属医院的科室列表
			List<HospitalDepartment> hdList= getHospitalDepartmentByHospId(new Long(hospitalList.get(i).getId()).intValue());
			List<DepartmentVo> departmentVoList= new ArrayList<>();
			//将List<HospitalDepartment> 转换成 List<DepartmentVo>
			for (int j = 0; j < hdList.size(); j++) {
				DepartmentVo departmentVo = new DepartmentVo();
				beanMapper.map(hdList.get(j), departmentVo);
				//判断该医生是否属于该科室
				departmentVo.setFlag(false);
				for (int k = 0; k < hospDrAssoList.size(); k++) {
					if(departmentVo.getId()==new Long(hospDrAssoList.get(k).getOfficeCode()).intValue()){
						departmentVo.setFlag(true);
						break;
					}
				}
				departmentVoList.add(departmentVo);
			}
			hospitalVo.setDepartmentList(departmentVoList);
			hospitalVoList.add(hospitalVo);
		}
		return hospitalVoList;
	}

	@Override
	public List<Hospital> dellShowData(HashMap<String, HashMap> dictHashMap,List<Hospital> hospitalList) {
		HashMap<Integer,String> hosp_lvlhashMap = dictHashMap.get("hosp_lvl");
		for (int i = 0; i < hospitalList.size(); i++) {
			hospitalList.get(i).setHosLevelString(hosp_lvlhashMap.get(hospitalList.get(i).getHosLevel()));
		}
		return hospitalList;
	}

	@Override
	public List<Hospital> searchByName(String name, String offset, String limit) {

		return hospitalMapper.searchByName(name, offset, limit);
	}

	@Override
	public Integer countByName(String name, String offset, String limit) {

		return hospitalMapper.countByName(name, offset, limit);
	}

	@Override
	public List<Hospital> listByIds(List<Long> ids) {
		return hospitalMapper.listByIds(ids);
	}


}
